<template>
  <div>
    <el-upload
      class="upload-demo"
      :headers="header"
      name="upfile"
      :limit="limit"
      :on-exceed="showText"
      :on-remove="removeList"
      action="/server/uploadUtil/upload"
      :on-error="handleAvatarError"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
      multiple
    >
     <el-button size="small" type="primary">点击上传</el-button>
     <span slot="tip" class="el-upload__tip" style="margin-left: 20px">文件不能超过{{size * 1024}}kb</span>
    </el-upload>
  </div>
</template>

<script>
export default {
  name: "igUpLoad",
  props: {
    size: {
      type: Number,
      default: 0.5
    },
    limit: {
      type: Number,
      default: 1
    }
  },
  data() {
    return {
      header: {
        //上传请求头
        token: JSON.parse(sessionStorage.getItem("loginMsg")).token,
        expire: JSON.parse(sessionStorage.getItem("loginMsg")).expire
      }
    };
  },
  methods: {
    removeList(file) { // 删除文件
      this.$emit("removeList", `${file.response.data.key}`);
    },
    showText() { // 超出数量限制提示
      this.$message.error(`上传文件最多只能上传${this.limit}个!`);
    },
    beforeAvatarUpload(file) {
      //上传验证
      const limit = file.size / 1024 / (this.size * 1024) < 1;
      if (!limit) {
        this.$message.error(`上传文件大小不能超过 ${this.size}M!`);
      }
      return limit;
    },
    handleAvatarSuccess(response, file, fileList) {
      //获取文件路径
      this.$emit("getUpLoad", `${response.data.key}`);
    },
    handleAvatarError(response, file, fileList) {
      this.$message.error("上传文件失败，请重试");
    }
  }
};
</script>

<style lang="scss" scoped>
</style>
